<template>
  <view class="dish-detail-container">
    <!-- 顶部导航栏按钮 -->
    <view class="nav-actions">
      <u-button icon="arrow-left" shape="circle" size="mini" @click="goBack" class="back-btn"></u-button>
      <u-button icon="share" shape="circle" size="mini" class="share-btn" @click="shareDish"></u-button>
    </view>
    
    <!-- 轮播图 -->
    <u-swiper
      class="swiper"
      :list="dishImages"
      keyName="url"
      :autoplay="true"
      :circular="true"
      :interval="3000"
      :duration="500"
      radius="0"
      indicatorMode="dot"
      :height="580"
    ></u-swiper>
    
    <!-- 菜品信息卡片 -->
    <view class="dish-info-card">
      <view class="dish-info">
        <view class="dish-name-row">
          <view class="dish-name">{{ dishDetail.name }}</view>
          <view class="dish-unit" v-if="dishDetail.unit">/{{ dishDetail.unit }}</view>
        </view>
        
        <view class="dish-price-row">
          <view class="dish-price">
            <text class="price-symbol">￥</text>
            <text class="price-value">{{ dishDetail.price?.toFixed(2) }}</text>
            <text v-if="dishDetail.originalPrice > dishDetail.price" class="price-original">￥{{ dishDetail.originalPrice?.toFixed(2) }}</text>
          </view>
          <view class="dish-rating-sales">
            <u-rate :value="dishDetail.rating || 4.5" readonly size="22" activeColor="#ff9900" inactiveColor="#eee"></u-rate>
            <text class="dish-sales">月售 {{ dishDetail.salesCount || 0 }}</text>
          </view>
        </view>
        
        <!-- 标签 -->
        <view class="dish-tags" v-if="dishDetail.tags && dishDetail.tags.length > 0">
          <u-tag 
            v-for="(tag, index) in dishDetail.tags" 
            :key="index" 
            :text="tag" 
            size="mini" 
            type="warning" 
            plain
            class="tag-item"
            shape="circle"
          ></u-tag>
        </view>
      </view>
      
      <!-- 描述 -->
      <view class="dish-section">
        <view class="section-title">
          <u-icon name="bookmark" color="#fa436a" size="28" class="section-icon"></u-icon>
          <text>菜品介绍</text>
        </view>
        <view class="dish-desc">{{ dishDetail.description || '暂无介绍' }}</view>
      </view>
      
      <!-- 规格 -->
      <view class="dish-section" v-if="dishDetail.specifications && dishDetail.specifications.length > 0">
        <view class="section-title">
          <u-icon name="setting" color="#fa436a" size="28" class="section-icon"></u-icon>
          <text>规格选择</text>
        </view>
        <view class="dish-specs">
          <u-button
            v-for="(spec, index) in dishDetail.specifications"
            :key="index"
            :text="spec"
            :type="selectedSpecIndex === index ? 'primary' : 'info'"
            size="mini"
            shape="circle"
            :plain="selectedSpecIndex !== index"
            class="spec-item"
            @click="selectSpec(index)"
          ></u-button>
        </view>
      </view>
      
      <!-- 推荐搭配 -->
      <view class="dish-section" v-if="recommendations.length > 0">
        <view class="section-title">
          <u-icon name="star" color="#fa436a" size="28" class="section-icon"></u-icon>
          <text>推荐搭配</text>
        </view>
        <scroll-view class="recommendations" scroll-x>
          <view 
            class="recommendation-item" 
            v-for="item in recommendations" 
            :key="item.id"
            @tap="navigateToDish(item.id)"
          >
            <u-image :src="item.imgUrl" width="160rpx" height="160rpx" borderRadius="12" class="rec-image"></u-image>
            <text class="rec-name">{{ item.name }}</text>
            <text class="rec-price">¥{{ item.price.toFixed(2) }}</text>
            <u-button icon="plus" size="mini" shape="circle" @click.stop="quickAddToCart(item)" class="rec-add-btn"></u-button>
          </view>
        </scroll-view>
      </view>
      
      <!-- 温馨提示 -->
      <view class="dish-section">
        <view class="section-title">
          <u-icon name="info-circle" color="#fa436a" size="28" class="section-icon"></u-icon>
          <text>温馨提示</text>
        </view>
        <view class="dish-tips">
          <view class="tip-item">· 图片仅供参考，实际以出品为准</view>
          <view class="tip-item">· 过敏体质人群请谨慎选择</view>
          <view class="tip-item">· 下单后{{ dishDetail.name }}将立即开始制作</view>
        </view>
      </view>
    </view>
    
    <!-- 加入购物车 -->
    <view class="action-bar">
      <view class="left-actions">
        <u-button icon="home" shape="circle" text="首页" plain size="mini" class="action-btn" @click="goToHome"></u-button>
        <u-button icon="shopping-cart" shape="circle" text="购物车" plain size="mini" class="action-btn" @click="goToCart">
          <u-badge 
            :count="cartItemCount" 
            :offset="[-8, -8]" 
            type="error" 
            size="mini" 
            v-if="cartItemCount > 0"
          ></u-badge>
        </u-button>
      </view>
      <view class="right-actions">
        <view class="quantity-control">
          <u-number-box 
            v-model="quantity" 
            :min="1" 
            :max="99" 
            disabledStyle="background-color: #f8f8f8;"
            bgColor="#fff"
            color="#fa436a"
            iconSize="22"
          ></u-number-box>
        </view>
        <view class="add-cart-btn">
          <u-button 
            type="primary" 
            text="加入购物车" 
            size="default" 
            shape="circle" 
            @click="addToCart"
            :customStyle="{background: 'linear-gradient(90deg, #fa436a, #F56C6C)'}"
          ></u-button>
        </view>
      </view>
    </view>
    
    <!-- 分享菜品弹窗 -->
    <u-popup v-model="showSharePopup" mode="bottom" borderRadius="24">
      <view class="share-popup">
        <view class="share-title">分享给好友</view>
        <view class="share-options">
          <view class="share-option" @tap="handleShare('wechat')">
            <u-icon name="weixin-fill" size="60" color="#07c160"></u-icon>
            <text>微信</text>
          </view>
          <view class="share-option" @tap="handleShare('moments')">
            <u-icon name="camera-fill" size="60" color="#fa436a"></u-icon>
            <text>朋友圈</text>
          </view>
          <view class="share-option" @tap="handleShare('link')">
            <u-icon name="link" size="60" color="#3c9cff"></u-icon>
            <text>复制链接</text>
          </view>
        </view>
        <view class="share-cancel">
          <u-button text="取消" plain @click="showSharePopup = false"></u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import * as uniApi from '@/common/utils/uni-api.js'
import cartStore from '@/common/store/cart.js'

// 数据
const id = ref('')
const dishDetail = ref({
  id: '1',
  name: '招牌柠打酱油柠檬茶',
  price: 18,
  originalPrice: 22,
  unit: '杯',
  rating: 4.8,
  salesCount: 238,
  tags: ['招牌', '酸甜', '人气TOP'],
  description: '雷公柠霸气推荐，被"雷击"过的味道！优选广东潮州的凤凰单丛雷打紫，茶汤金亮，高山气韵雄浑勃发，芝兰花香清新悠扬。加入香水柠檬，内敛与清爽激发香气层次。',
  specifications: ['常规', '加冰', '少冰', '去冰'],
  size: '600ml'
})
const quantity = ref(1)
const selectedSpecIndex = ref(0)
const showSharePopup = ref(false)

// 推荐菜品示例数据
const recommendations = reactive([
  {
    id: '2',
    name: '暴打凤梨鸭屎香柠檬茶',
    price: 18,
    imgUrl: 'https://img0.baidu.com/it/u=1231988636,1468877653&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500'
  },
  {
    id: '3',
    name: '暴打凤梨冰红茶',
    price: 16,
    imgUrl: 'https://img1.baidu.com/it/u=3392835995,346222449&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
  },
  {
    id: '4',
    name: '橙多芬冰红茶',
    price: 16,
    imgUrl: 'https://img0.baidu.com/it/u=3778196502,2840227022&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
  }
])

// 轮播图
const dishImages = computed(() => {
  return [
    { url: 'https://img2.baidu.com/it/u=1847215506,997905894&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500' },
    { url: 'https://img0.baidu.com/it/u=1231988636,1468877653&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500' },
    { url: 'https://img1.baidu.com/it/u=3392835995,346222449&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500' }
  ]
})

// 购物车相关
const cartItemCount = computed(() => {
  return cartStore.getCartItemCount()
})

// 方法
const goBack = () => {
  uniApi.navigateBack()
}

const goToHome = () => {
  uniApi.switchTab('/pages/index/index')
}

const goToCart = () => {
  uniApi.navigateTo('/pages/cart/cart')
}

const selectSpec = (index) => {
  selectedSpecIndex.value = index
}

const addToCart = () => {
  // 获取选择的规格
  const selectedSpec = dishDetail.value.specifications ? 
    dishDetail.value.specifications[selectedSpecIndex.value] : ''
  
  // 构建购物车项
  const cartItem = {
    id: dishDetail.value.id,
    name: dishDetail.value.name,
    price: dishDetail.value.price,
    imgUrl: dishImages.value[0].url,
    quantity: quantity.value,
    specification: selectedSpec
  }
  
  // 添加到购物车
  cartStore.addToCart(cartItem)
  
  // 提示
  uniApi.showToast(`已添加 ${cartItem.quantity} 杯 ${cartItem.name} 到购物车`)
}

const quickAddToCart = (item) => {
  const cartItem = {
    id: item.id,
    name: item.name,
    price: item.price,
    imgUrl: item.imgUrl,
    quantity: 1
  }
  
  cartStore.addToCart(cartItem)
  uniApi.showToast(`已添加 ${item.name} 到购物车`)
}

const navigateToDish = (dishId) => {
  uniApi.navigateTo(`/pages/dish/detail?id=${dishId}`)
}

const shareDish = () => {
  showSharePopup.value = true
}

const handleShare = (platform) => {
  let message = ''
  
  switch (platform) {
    case 'wechat':
      message = '已分享到微信'
      break
    case 'moments':
      message = '已分享到朋友圈'
      break
    case 'link':
      // 获取链接
      const link = `https://example.com/dish/${dishDetail.value.id}`
      
      // 复制到剪贴板
      uni.setClipboardData({
        data: link,
        success: () => {
          message = '链接已复制'
        }
      })
      break
  }
  
  if (message) {
    uniApi.showToast(message)
  }
  
  showSharePopup.value = false
}

// 获取菜品详情
const getDishDetail = async (dishId) => {
  try {
    // 这里应该是API请求，这里模拟数据
    // const res = await api.dishApi.getDishDetail(dishId)
    // dishDetail.value = res.data
    
    // 模拟数据已经在上面初始化了
    console.log('获取菜品详情', dishId)
  } catch (e) {
    console.error('获取菜品详情失败', e)
    uniApi.showToast('获取菜品详情失败')
  }
}

// 页面加载
onMounted(() => {
  // 获取页面参数
  const query = uni.$route?.query || {}
  
  if (query.id) {
    id.value = query.id
    getDishDetail(id.value)
  }
})
</script>

<style lang="scss" scoped>
.dish-detail-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  position: relative;
  padding-bottom: 140rpx;
}

.nav-actions {
  position: absolute;
  top: 60rpx;
  left: 0;
  right: 0;
  z-index: 10;
  display: flex;
  justify-content: space-between;
  padding: 0 30rpx;
}

.back-btn, .share-btn {
  background-color: rgba(255, 255, 255, 0.8) !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.swiper {
  width: 100%;
  height: 580rpx;
}

.dish-info-card {
  margin-top: -40rpx;
  background-color: #fff;
  border-radius: 40rpx 40rpx 0 0;
  padding: 30rpx;
  position: relative;
  z-index: 2;
}

.dish-info {
  padding-bottom: 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.dish-name-row {
  display: flex;
  align-items: flex-end;
  margin-bottom: 16rpx;
}

.dish-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.dish-unit {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
  margin-bottom: 6rpx;
}

.dish-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.dish-price {
  display: flex;
  align-items: baseline;
}

.price-symbol {
  font-size: 24rpx;
  color: #fa436a;
}

.price-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #fa436a;
}

.price-original {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
  margin-left: 10rpx;
}

.dish-rating-sales {
  display: flex;
  align-items: center;
}

.dish-sales {
  font-size: 24rpx;
  color: #999;
  margin-left: 16rpx;
}

.dish-tags {
  display: flex;
  flex-wrap: wrap;
}

.tag-item {
  margin-right: 10rpx;
  margin-bottom: 6rpx;
}

.dish-section {
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.dish-section:last-child {
  border-bottom: none;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.section-icon {
  margin-right: 10rpx;
}

.dish-desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
}

.dish-specs {
  display: flex;
  flex-wrap: wrap;
}

.spec-item {
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}

.recommendations {
  white-space: nowrap;
}

.recommendation-item {
  display: inline-block;
  width: 160rpx;
  margin-right: 30rpx;
  position: relative;
  vertical-align: top;
}

.rec-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  margin-bottom: 10rpx;
}

.rec-name {
  font-size: 24rpx;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 6rpx;
}

.rec-price {
  font-size: 24rpx;
  color: #fa436a;
  font-weight: bold;
}

.rec-add-btn {
  position: absolute;
  right: 0;
  bottom: 0;
  transform: scale(0.8);
  transform-origin: bottom right;
}

.dish-tips {
  font-size: 24rpx;
  color: #999;
  line-height: 1.6;
}

.tip-item {
  margin-bottom: 10rpx;
}

.action-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 120rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  z-index: 10;
}

.left-actions {
  display: flex;
}

.action-btn {
  margin-right: 20rpx;
}

.right-actions {
  display: flex;
  align-items: center;
}

.quantity-control {
  margin-right: 30rpx;
}

.add-cart-btn {
  min-width: 240rpx;
}

.share-popup {
  padding: 40rpx;
}

.share-title {
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 40rpx;
}

.share-options {
  display: flex;
  justify-content: space-around;
  padding: 0 40rpx;
  margin-bottom: 60rpx;
}

.share-option {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.share-option text {
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #666;
}

.share-cancel {
  margin-top: 20rpx;
}
</style> 